package com.hitqz.robot.driver.netty.strategy;

import com.google.common.util.concurrent.RateLimiter;
import com.hitqz.robot.driver.dto.GfRelayStatus;
import com.hitqz.robot.driver.netty.protocol.message.GfMessage;
import com.hitqz.robot.driver.util.GfCacheUtil;
import com.hitqz.robot.driver.util.GfToolkit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 消息解析，只做信息保存或者发布事件，不做业务逻辑处理
 */
@Slf4j
public class Gf80Strategy implements GfMessageHandlerStrategy {

    private final static RateLimiter logLimiter = RateLimiter.create(1);

    @Override
    public void handle(ChannelHandlerContext ctx, GfMessage message) {
        // 获取消息中的数据
        byte[] data = message.getData();
        int mainCmd = data[0] & 0xFF;//转换为无符号
        int subCmd = data[1] & 0xFF;//转换为无符号
        boolean reslut = true;
        // 分配 ByteBuf 并将数据写入
        ByteBuf buffer = ctx.alloc().buffer(data.length);
        buffer.writeBytes(data);
        try {
            mainCmd = buffer.readByte() & 0xFF;
            subCmd = buffer.readByte() & 0xFF;
            switch (subCmd) {
                case 0x01 -> reslut = buffer.readByte() == (byte)0x00;
                case 0x02-> {
                    //获取继电器状态
                    int relay1Status = buffer.readByte()& 0xFF;
                    int relay2Status = buffer.readByte()& 0xFF;
                    GfRelayStatus relays = GfRelayStatus.builder().status1(relay1Status).status2(relay2Status).build();
                    GfCacheUtil.putLongtimeCache(GfCacheUtil.KEY_ROBOT_STATUS,relays);
                }
            }
            GfToolkit.release(message, true, reslut);
        } catch (Exception e) {
            log.error("[gf]deal  {}{}-message error,{}", String.format("%02x", mainCmd), String.format("%02x", subCmd), e.getMessage());
        } finally {
            // 确保 ByteBuf 在使用完后释放，防止内存泄漏
            buffer.release();
        }
    }


}
